<template>
  <!-- 上传清洗记录 -->
  <view class="addUploadrinse">
    <view class="content">
      <view class="content-item">
        <u-form
          :model="form"
          ref="form"
          label-width="100"
          :error-type="errorType"
        >
          <view class="inputPad">
            <u-form-item
              label="选择餐厅"
              borderBottom
              :required="true"
              @click="cellClick('name', 'restaurantIdDesc')"
            >
              <u--input
                v-model="form.restaurantIdDesc"
                readonly
                disabledColor="#ffffff"
                placeholder="请选择"
                placeholderClass="placeholderClass"
                inputAlign="right"
                border="none"
              ></u--input>
              <u-icon slot="right" name="arrow-right"></u-icon>
            </u-form-item>
          </view>
          <u-form-item label="清洗厂商" borderBottom :required="true">
            <u--input
              v-model.trim="form.serviceProvider"
              border="none"
              placeholder="请填写"
              placeholderClass="placeholderClass"
              inputAlign="right"
              :maxlength="30"
            ></u--input>
          </u-form-item>
          <u-form-item label="清洗联系电话" borderBottom :required="true">
            <u--input
              v-model.trim="form.contactsPhone"
              border="none"
              placeholder="请填写"
              placeholderClass="placeholderClass"
              inputAlign="right"
              :maxlength="11"
              @blur="phoneHandle"
            ></u--input>
          </u-form-item>

          <u-form-item label="清洗日期" borderBottom :required="true">
            <u--input
              v-model.trim="form.cleanTimeName"
              border="none"
              placeholder=""
              placeholderClass="placeholderClass"
              inputAlign="right"
              readonly
            ></u--input>
          </u-form-item>

          <!-- 不要删 -->
          <!-- <view class="inputPad">
            <u-form-item
              label="清洗日期"
              borderBottom
              :required="true"
              @click="cellTimeClick('cleanTimeName')"
            >
              <u--input
                v-model.trim="form.cleanTimeName"
                readonly
                disabledColor="#ffffff"
                placeholder="请选择"
                placeholderClass="placeholderClass"
                inputAlign="right"
                border="none"
              ></u--input>
              <u-icon slot="right" name="arrow-right"></u-icon>
            </u-form-item>
          </view> -->
        </u-form>

        <block v-if="scale != 1">
          <view class="deal-title">
            <text class="required reqText">*</text>
            净化设备现场清洗照片
            <text class="state">（上传4张）</text>
          </view>
          <view class="upload-view">
            <u-upload
              :fileList="fileList"
              @afterRead="afterRead"
              @delete="deletePic"
              name="file"
              :maxCount="4"
              :multiple="true"
              width="100"
              height="90"
            >
              <image
                :src="baseImgUrl + 'upload-icon.png'"
                style="width: 200rpx; height: 180rpx"
              ></image>
            </u-upload>
          </view>
        </block>

        <view class="deal-title">
          <text class="required reqText">*</text>
          排风机现场清洗照片
          <text class="state">（上传4张）</text>
        </view>
        <view class="upload-view">
          <u-upload
            :fileList="fileList2"
            @afterRead="afterRead2"
            @delete="deletePic2"
            name="file"
            :maxCount="4"
            :multiple="true"
            width="100"
            height="90"
          >
            <image
              :src="baseImgUrl + 'upload-icon.png'"
              style="width: 200rpx; height: 180rpx"
            ></image>
          </u-upload>
        </view>

        <block v-if="scale != 1">
          <view class="deal-title">
            <text class="required reqText">*</text>
            烟道机现场清洗照片
            <text class="state">（上传4张）</text>
          </view>
          <view class="upload-view">
            <u-upload
              :fileList="fileList3"
              @afterRead="afterRead3"
              @delete="deletePic3"
              name="file"
              :maxCount="4"
              :multiple="true"
              width="100"
              height="90"
            >
              <image
                :src="baseImgUrl + 'upload-icon.png'"
                style="width: 200rpx; height: 180rpx"
              ></image>
            </u-upload>
          </view>
        </block>

        <view class="deal-title"> 备注信息 </view>
        <view class="thein-area">
          <u--textarea
            v-model="situation"
            placeholder="请简单描述清洗情况"
            count
            maxlength="50"
            placeholder-class="aaccd"
            height="135"
          ></u--textarea>
        </view>
      </view>
    </view>

    <view class="btns">
      <button
        class="reset-btn lt cancelBtn"
        type="primary"
        @click="resethandle"
      >
        取消
      </button>
      <button class="submit-btn" type="primary" @click="submitHandle">
        保存
      </button>
    </view>

    <u-picker
      :show="pickerShow"
      :columns="columns"
      :keyName="keyName"
      @confirm="showConfirm"
      @close="pickerClose"
      @cancel="pickerCancel"
      :closeOnClickOverlay="true"
    ></u-picker>

    <!-- 时间选择器 -->
    <u-datetime-picker
      ref="datetimePicker"
      :show="datetimeShow"
      v-model="timeValue"
      mode="date"
      :formatter="formatter"
      :minDate="minDate"
      :maxDate="maxDate"
      @close="pickerTimeClose"
      @cancel="pickerTimeClose(1)"
      @confirm="showTimeConfirm"
      :closeOnClickOverlay="true"
    ></u-datetime-picker>
  </view>
</template>

<script>
import { cleanRecordCreate } from "@/api/home.js";
import { restaurantList } from "@/api/myself.js";
import {
  Toast,
  navBack,
  formatters,
  dayTurnTime,
  regPhone,
  uniTrim,
} from "@/utils/util.js";
import mixin from "@/utils/mixin.js";

export default {
  name: "addUploadrinse",
  mixins: [mixin],
  data() {
    return {
      baseImgUrl: this.$baseImgUrl,
      baseURL: this.$baseURL,
      form: {},
      errorType: ["none"],
      purifyImageList: [],
      fenImageList: [],
      smokeImageList: [],
      fileList: [],
      fileList2: [],
      fileList3: [],
      scale: "", // 餐厅大小
      situation: "",
    };
  },
  onShow() {
    this.$set(this.form, "cleanTimeName", formatters(new Date(), "YY/MM/DD"));
    this.$set(this.form, "cleanTime", dayTurnTime(this.form.cleanTimeName));
  },
  methods: {
    formatter(type, value) {
      if (type === "year") {
        return `${value}年`;
      }
      if (type === "month") {
        return `${value}月`;
      }
      if (type === "day") {
        return `${value}日`;
      }
      return value;
    },
    cellTimeClick(e) {
      this.cellType = e;
      var minDateNum = +new Date(); //获取当前时间的毫秒数

      switch (this.cellType) {
        case "cleanTimeName":
          this.maxDate = minDateNum;
          this.timeValue = this.maxDate;
          break;
        default:
          break;
      }

      setTimeout(() => {
        this.datetimeShow = true;
      }, 100);
    },
    pickerTimeClose(e) {
      if (e) {
        switch (this.cellType) {
          case "cleanTimeName":
            this.form.cleanTime = "";
            this.form.cleanTimeName = "";
            break;
          default:
            break;
        }
      }
      this.datetimeShow = false;
    },
    /* 时间选择器 确定 */
    showTimeConfirm(e) {
      let arr = e.value;
      if (arr) {
        switch (this.cellType) {
          case "cleanTimeName":
            this.form.cleanTimeName = formatters(arr, "YY/MM/DD");
            this.form.cleanTime = dayTurnTime(this.form.cleanTimeName);
            break;

          default:
            break;
        }
      }
      this.datetimeShow = false;
    },
    /* cell 点击 */
    cellClick(name, type) {
      this.keyName = name;
      this.cellType = type;
      let code = "";
      switch (this.cellType) {
        case "restaurantIdDesc":
          code = "restaurantIdDesc";
          break;
        default:
          break;
      }

      if (code == "restaurantIdDesc") {
        restaurantList().then((res) => {
          this.columns[0] = res.result || [];
          this.pickerShow = true;
        });
      }
    },
    /* 选择器 确定 */
    showConfirm(e) {
      let arr = e.value;
      if (arr.length) {
        let obj = arr[0];
        switch (this.cellType) {
          case "restaurantIdDesc":
            this.form.restaurantId = obj.id;
            this.form.restaurantIdDesc = obj.name;
            this.scale = obj.scale;
            if (obj.scale == 1) {
              this.purifyImageList = [];
              this.smokeImageList = [];
              this.fileList = [];
              this.fileList3 = [];
            }
            break;
          default:
            break;
        }
      }
      this.pickerShow = false;
    },
    phoneHandle() {
      if (this.form.contactsPhone && !regPhone(this.form.contactsPhone)) {
        Toast("请输入正确的联系电话");
        return;
      }
    },
    afterRead(info) {
      let _this = this;
      for (let v of info.file) {
        uni.uploadFile({
          url: _this.baseURL + "/mini/sys/upload/upload_file",
          filePath: v.url,
          name: "file",
          header: {
            "content-type": "application/json", // 默认值
            "X-MINI-TOKEN": uni.getStorageSync("X-MINI-TOKEN"),
          },
          formData: {
            type: 8,
          },
          success(res) {
            let { fullPath, halfPath } = JSON.parse(res.data).result;
            _this.fileList.push({ url: fullPath });
            _this.purifyImageList.push(halfPath);
          },
        });
      }
    },
    afterRead2(info) {
      let _this = this;
      for (let v of info.file) {
        uni.uploadFile({
          url: _this.baseURL + "/mini/sys/upload/upload_file",
          filePath: v.url,
          name: "file",
          header: {
            "content-type": "application/json", // 默认值
            "X-MINI-TOKEN": uni.getStorageSync("X-MINI-TOKEN"),
          },
          formData: {
            type: 9,
          },
          success(res) {
            let { fullPath, halfPath } = JSON.parse(res.data).result;
            _this.fileList2.push({ url: fullPath });
            _this.fenImageList.push(halfPath);
          },
        });
      }
    },
    afterRead3(info) {
      let _this = this;
      for (let v of info.file) {
        uni.uploadFile({
          url: _this.baseURL + "/mini/sys/upload/upload_file",
          filePath: v.url,
          name: "file",
          header: {
            "content-type": "application/json", // 默认值
            "X-MINI-TOKEN": uni.getStorageSync("X-MINI-TOKEN"),
          },
          formData: {
            type: 10,
          },
          success(res) {
            let { fullPath, halfPath } = JSON.parse(res.data).result;
            _this.fileList3.push({ url: fullPath });
            _this.smokeImageList.push(halfPath);
          },
        });
      }
    },
    deletePic(e) {
      this.fileList.splice(e.index, 1);
      this.purifyImageList.splice(e.index, 1);
    },
    deletePic2(e) {
      this.fileList2.splice(e.index, 1);
      this.fenImageList.splice(e.index, 1);
    },
    deletePic3(e) {
      this.fileList3.splice(e.index, 1);
      this.smokeImageList.splice(e.index, 1);
    },
    resethandle() {
      uni.navigateBack();
    },
    submitHandle() {
      let { restaurantId, serviceProvider, contactsPhone, cleanTime } =
        this.form;

      if (!restaurantId) {
        Toast("请选择餐厅");
        return;
      }

      if (!serviceProvider || !uniTrim(serviceProvider)) {
        Toast("请输入清洗厂商");
        return;
      }

      if (!contactsPhone) {
        Toast("请输入清洗联系电话");
        return;
      }

      if (!regPhone(contactsPhone)) {
        Toast("请输入正确的联系电话");
        return;
      }

      // if (!cleanTime) {
      //   Toast("请选择清洗日期");
      //   return;
      // }

      if (this.scale != 1 && !this.purifyImageList.length) {
        Toast("净化设备现场清洗照片至少上传1张图片");
        return;
      }

      if (!this.fenImageList.length) {
        Toast("排风机现场清洗照片至少上传1张图片");
        return;
      }

      if (this.scale != 1 && !this.smokeImageList.length) {
        Toast("烟道机现场清洗照片至少上传1张图片");
        return;
      }

      let data = {
        restaurantId,
        serviceProvider,
        contactsPhone,
        cleanTime,
        purifyImageList: this.purifyImageList,
        fenImageList: this.fenImageList,
        smokeImageList: this.smokeImageList,
        situation: this.situation,
      };

      cleanRecordCreate(data).then((res) => {
        if (res.code == 200) {
          Toast("保存成功");
          navBack("back");
          return;
        }

        Toast(res.message);
      });
    },
  },
};
</script>

<style lang="scss">
.addUploadrinse {
  flex: 1;
  background-color: #f9f9f9;

  .content {
    margin: 0 auto;
    margin-top: 20rpx;
    margin-bottom: 20rpx;
    border-radius: 8rpx;
    width: calc(100% - 35rpx);
    height: calc(100vh - 84px);
    overflow-y: auto;
    background: #fff;

    .content-item {
      padding: 25rpx;

      .deal-title {
        position: relative;
        padding: 20rpx 0;
        color: #303133;
        font-size: 30rpx;
        font-weight: 500;

        .state {
          color: #a1a1a1;
          font-size: 26rpx;
        }

        .reqText {
          position: absolute;
          left: -16rpx;
        }
      }

      .thein-area {
        font-size: 28rpx;
        .u-textarea--radius,
        .u-textarea__count {
          background: #f9f9f9 !important;
        }

        .u-textarea__field {
          font-size: 28rpx;
        }
      }
    }
  }
}
</style>
